package com.example.hp.serviceproject;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Environment;
import android.os.IBinder;

public class MusicService extends Service {
    private MediaPlayer player;
    private String mp3Path="";
    private boolean isPause=false;
    public MusicService() {
    }



    @Override
    public void onCreate() {
        super.onCreate();
        mp3Path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/mp3/";
        //idle
        player=new MediaPlayer();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        String action = intent.getStringExtra("action");
        String music=intent.getStringExtra("music");
        switch (action){
            case "play":
                try {
                    play(music);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "pause":
                pause();
        }
        return Service.START_NOT_STICKY;
    }

    private  void play(String music) throws Exception{
        if(!isPause) {
            player.reset();
            player.setDataSource(mp3Path + music);
            player.prepare();
        }
        player.start();
        isPause=false;
    }

    private void pause(){
        player.pause();
        isPause=true;
    }


    @Override
    public IBinder onBind(Intent intent) {

        throw new UnsupportedOperationException("Not yet implemented");
    }
}
